package imgctl

import (
	"context"
	"encoding/base64"
	"net/http"

	"code.bydev.io/cht/customer/kyc_admin_service/internal/pkg/biz"
	"code.bydev.io/cht/customer/kyc_admin_service/internal/pkg/kycadminapi"
	"code.bydev.io/cht/customer/kyc_admin_service/internal/pkg/kycadminapi/actionsvc"
	"go.uber.org/zap"
)

type ImgCtrl = *imgCtrl

type imgCtrl struct {
	logger *zap.Logger
	teller kycadminapi.Teller
	acvSvc actionsvc.ActionSvc
}

func New(h *biz.Handler) ImgCtrl {
	return &imgCtrl{
		logger: h.Logger(),
		teller: h.Teller(),
		acvSvc: actionsvc.New(h.KycAdminRepo(), h.SecHub(), h.Logger(), h.Teller()),
	}
}

func (s *imgCtrl) DownloadHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	tokenBt, err := base64.RawStdEncoding.DecodeString(r.URL.Query().Get("token"))
	if err != nil {
		s.logger.Error("token DecodeString error", zap.Error(err))
		w.WriteHeader(http.StatusNotFound)
		_, _ = w.Write([]byte(""))
		return
	}

	token := string(tokenBt)
	if token == "" {
		s.logger.Info("token empty")
		w.WriteHeader(http.StatusNotFound)
		_, _ = w.Write([]byte(""))

		return
	}

	s.logger.Info("image token", zap.Any("token", token))
	body, ln, err := s.acvSvc.GetActionImage(ctx, token)
	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		_, _ = w.Write([]byte(""))

		return
	}
	if body == nil || ln == 0 {
		w.WriteHeader(http.StatusNotFound)
		_, _ = w.Write([]byte(""))
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", http.DetectContentType(body))
	bl, err := w.Write(body)
	if err != nil {
		s.logger.Error("write response failed", zap.Error(err))
		return
	}
	s.logger.Info("write response success", zap.Int("byte length", bl))
}
